import { ref } from 'vue'
import { getSetting } from '@/api/setting'
import { titleController } from '@/utils'
import type { settings } from '@/types/settings'
import { defineStore } from 'pinia'

export const useSettings = defineStore('settings', () => {
  const loading = ref(false)
  const data = ref<settings | null>(null)
  function setLoading(status: boolean) {
    loading.value = status
  }
  function setData(payload: settings) {
    data.value = payload
  }
  async function fetchSetting() {
    setLoading(true)
    const resp = await getSetting()
    // console.log(JSON.stringify(resp), '<---setting');
    setData(resp)
    setLoading(false)
    if (resp.favicon) {
      // <link rel="shortcut icon " type="images/x-icon" href="./favicon.ico">
      let link = document.querySelector("link[ref='shortcut icon']") as HTMLLinkElement
      link = document.createElement('link')
      link.rel = 'shortcut icon'
      link.type = 'images/x-icon'
      link.href = resp.favicon
      document.querySelector('head')?.appendChild(link)
    }
    if (resp.siteTitle) {
      titleController.setSiteTitle(resp.siteTitle)
    }
  }
  return {
    // loading,
    data,
    fetchSetting
  }
})
